package com.rjwh.dingdong.client.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.baidu.mobstat.StatService;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.widget.MyProgressDialog;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseFragment extends Fragment {
    private MyProgressDialog mProgressDialog;
    public CompositeSubscription mCompositeSubscription;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        StatService.onPause(getContext());
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        StatService.onResume(getContext());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        onUnsubscribe();
    }

    public void showLoadDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            return;
        }
        String title = getResources().getString(R.string.dialog_title_waitting);
        try {
            if (mProgressDialog == null) {
                mProgressDialog = new MyProgressDialog(getActivity(), title);
                mProgressDialog.show();
            } else if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }
        } catch (Exception e) {
            LogUtil.d("BaseActivity", "progressDialog error", e);
        }
    }

    public void dismissLoadDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    public void addSubscription(Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscriber);
    }
}
